package com.ks.springcloud.controller;

import com.ks.springcloud.entity.CommonResult;
import com.ks.springcloud.entity.Payment;
import com.ks.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author：Administrator
 * @Date：2022/3/3/0003 23:51
 * @Versiion：1.0
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    /**注册进eureka的服务 用服务名代替*/
    private static final String PAYMENT_URL = "HTTP://CLOUD-PAYMENT-SERVICE";

    /***
     * Ribbon = ribbon  +  restTemplate
     * 其实 restTemplate对ribbon封装
     * 常用的方式是：
     * getForObject/getForEntity
     * postForObject/postForEntity
     */
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer  loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/getDiscoverys")
    public CommonResult<Payment> getDiscoverys(){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/getDiscoverys",CommonResult.class);
    }

    @GetMapping(value = "/consumer/payment/lb")
    public String getPaymentLB(){
        //获取当前注册中心的所有服务集合
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(CollectionUtils.isEmpty(instances)){
            return null;
        }
        //通过自实现的负载均衡选择服务
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        //获取实例的uri
        return restTemplate.getForObject(serviceInstance.getUri()+"/payment/payment/lb", String.class);
    }
}
